const util = require('../../utils/util.js');
const api = require('../../config/api.js');
const user = require('../../services/user.js');
const banner = require('../../services/banner.js');
const goods = require('../../services/goods.js');

//获取应用实例
const app = getApp()
let canUseReachBottom = true;//触底函数控制变量
Page({
    data: {
        openAttr: false,
        goodsCount: 0,
        banners: [],
        userInfo: {},
        imgurl: '',
        sysHeight: 0,
        loading: 0,
        autoplay: true,
        navs: [],
        cates: [],
        x: 0,
        y: 0,
        cateShow: false,
        xSelected: 0,
        groupTime: '',
        groups: [],
        news: [],
        discounts: [],
        goods: [],
        page: 1,
        noMore: true,
    },
    onHide: function () {
        this.setData({
            autoplay: false
        })
    },
    clickIcon: function (e) {
        let type = e.currentTarget.dataset.type;
        this.setData({
            cateShow: !type
        })
    },
    switchTap: function (e) {
        let that = this;
        let d = e.currentTarget.dataset;
        let screenWidth = wx.getSystemInfoSync().windowWidth;
        let itemWidth = screenWidth / 7; // 平均宽度
        let index = d.index; // 索引
        let cate_id = d.id; // 唯一id
        const navData = that.data.navs; // 导航数据列表
        let scrollX = itemWidth * index - itemWidth * 3; // 当前宽度
        let maxScrollX = (navData.length + 1) * itemWidth; // 最大宽度
        if (scrollX < 0) {
            scrollX = 0;
        } else if (scrollX >= maxScrollX) {
            scrollX = maxScrollX;
        }
        util.request(api.CatesCurrent, {id: cate_id}).then(function (ret) {
            if (ret.code == 0) {
                that.setData({
                    cates: ret.data,
                    x: scrollX,
                    xSelected: cate_id,
                    cateShow: false,
                    goods: [],
                    y: 0
                })
            }
        });
        banner.getBanner(cate_id).then(function (tx) {
            if (tx.code == 0) {
                that.setData({
                    banners: tx.data
                })
            }
        });
        let page = 1;
        goods.getGoods(cate_id, page).then(function (gs) {
            if (gs.code == 0) {
                // 充值
                that.setData({
                    page: page,
                    goods: gs.data
                })
            }
        })
    },
    navClick: function (e) {
        let that = this;
        let d = e.currentTarget.dataset
        let screenWidth = wx.getSystemInfoSync().windowWidth;
        let itemWidth = screenWidth / 7; // 平均宽度
        let scrollX = itemWidth * d.index - itemWidth * 3; // 当前宽度
        let cate_id = d.id; // 唯一id
        // 数据请求
        util.request(api.CatesCurrent, {id: cate_id}).then(function (ret) {
            if (ret.code == 0) {
                that.setData({
                    cates: ret.data,
                    x: scrollX,
                    xSelected: cate_id,
                    cateShow: false,
                    goods: [],
                    y: 0
                })
            }
        });
        // 轮播图获取
        banner.getBanner(cate_id).then(function (tx) {
            if (tx.code == 0) {
                that.setData({
                    banners: tx.data
                })
            }
        });
        // 商品
        let page = 1;
        goods.getGoods(cate_id, page).then(function (gs) {
            if (gs.code == 0) {
                // 充值
                that.setData({
                    page: page,
                    goods: gs.data
                })
            }
        })
    },
    goSearch: function () {
        wx.navigateTo({
            url: '/pages/search/search',
        })
    },
    clickMore: function (params) {
        wx.navigateToMiniProgram({
            appId: 'wxd9813e0a0d4d4156'
        })
    },
    goCategory: function (e) {
        let id = e.currentTarget.dataset.cateid;
        wx.setStorageSync('categoryId', id);
        wx.switchTab({
            url: '/pages/category/index',
        })
    },
    getCatalog: function () {
        let that = this;
        util.request(api.GoodsCount).then(function (res) {
            if (res.code == 0) {
                that.setData({
                    goodsCount: res.data.count
                });
            }
        });
    },
    getCate: function () {
        let that = this;
        let page = this.data.page;
        util.request(api.CatesIndex, {'sign': 'home'}).then(function (res) {
            if (res.code == 0) {
                that.setData({
                    navs: res.data,
                    xSelected: res.data[0].id,
                    loading: 1
                });
                let cateId = res.data[0].id;
                util.request(api.CatesCurrent, {id: cateId}).then(function (ret) {
                    if (ret.code == 0) {
                        that.setData({
                            cates: ret.data
                        })
                    }
                });
                banner.getBanner(cateId).then(function (tx) {
                    if (tx.code == 0) {
                        that.setData({
                            banners: tx.data
                        })
                    }
                });
                goods.getGoods(cateId, page).then(function (gs) {
                    if (gs.code == 0) {
                        that.setData({
                            goods: gs.data
                        })
                    }
                })
            }
        });
    },
    bannerClick: function (e) {
        // 点击跳转
        let url = e.currentTarget.dataset.url;
        if (url) {
            wx.navigateTo({
                url: url,
            })
        }
    },
    getGroup: function () {
        let that = this;
        util.request(api.GroupIndex).then(function (res) {
            if (res.code == 0) {
                that.setData({
                    groupTime: res.data.group_time,
                    groups: res.data.list
                })
            }
        })
    },
    getActivity: function () {
        let that = this;
        util.request(api.ActivityIndex).then(function (res) {
            if (res.code == 0) {
                that.setData({
                    discounts: res.data
                })
            }
        })
    },
    handleTap: function (event) {
        //阻止冒泡 
    },
    onShareAppMessage: function () {
        let info = wx.getStorageSync('userInfo');
        return {
            title: '亚唯物',
            desc: '电商小程序',
            path: '/pages/index/index?id=' + info.id
        }
    },
    onLoad: function (options) {
        let systemInfo = wx.getStorageSync('systemInfo');
        let scene = decodeURIComponent(options.scene);
        // 商品总数
        this.getCatalog();
        // 商品分类
        this.getCate();
    },
    onShow: function () {
        // 拼团信息
        this.getGroup();
        // 活动展示
        this.getActivity();
        // 购物车数量
        this.getCartNum();
        let that = this;
        let userInfo = wx.getStorageSync('userInfo');
        if (userInfo != '') {
            that.setData({
                userInfo: userInfo,
            });
        }
        let info = wx.getSystemInfoSync();
        let sysHeight = info.windowHeight - 422;
        this.setData({
            sysHeight: sysHeight,
            autoplay: true
        });
        wx.removeStorageSync('categoryId');
    },
    getCartNum: function () {
        let token = wx.getStorageSync('token');
        util.request(api.CartGoodsCount, {token: token}, "POST").then(function (res) {
            if (res.code == 0) {
                let cartGoodsCount = '';
                if (res.data == 0) {
                    wx.removeTabBarBadge({
                        index: 2,
                    })
                } else {
                    cartGoodsCount = res.data + '';
                    wx.setTabBarBadge({
                        index: 2,
                        text: cartGoodsCount
                    })
                }
            }
        });
    },
    scrollToLower: function (e) {
        if (!canUseReachBottom) return;//如果触底函数不可用，则不调用网络请求数据
        let that = this;
        let cateId = that.data.xSelected;
        let page = that.data.page + 1;
        let no = that.data.noMore;
        if (this.data.noMore) {
            wx.showLoading({
                title: '',
                mask:true
            });
            canUseReachBottom = false;//触底函数关闭
            goods.getGoods(cateId, page).then(function (res) {
                if (res.data.length > 0 && no) {
                    that.setData({
                        page: page,
                        goods: that.data.goods.concat(res.data)
                    })
                } else {
                    that.setData({
                        noMore: false
                    })
                }
                canUseReachBottom = true;//有新数据，触底函数开启，为下次触底调用做准备
                wx.hideLoading();
            });
        }
    },
    clickImage: function (e) {
        let goodsId = e.currentTarget.dataset.id
        let type = e.currentTarget.dataset.type
        wx.navigateTo({
            url: '/pages/goods/goods?id=' + goodsId + '&type=' + type
        })
    },
    onPullDownRefresh: function () {
        wx.showNavigationBarLoading()
        wx.hideNavigationBarLoading() //完成停止加载
        wx.stopPullDownRefresh() //停止下拉刷新
    },
})